package com.ygxsk.carhome.ui.archive;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.LeadListItemBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusLeadMember;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.LeadManMemberAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/2/21  12:03
 * @Description:是潜客的 客户信息 携带到客户信息之中
 */
public class LeadsDataActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutinleadsdata)
    SmartRefreshLayout refreshLayoutInLeadData;

    @BindView(R.id.recyclerviewinleaddata)
    RecyclerView recyclerViewInLeadData;

    //点击确定的按钮
    @BindView(R.id.roundbuttonsurechooselead)
    RoundTextView roundButtonSureChooseLead;

    //潜客信息 列表
    private ArrayList<LeadListItemBean> mDatasResources = new ArrayList<>();

    private LeadManMemberAdapter leadManMemberAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();


    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_leads_data;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.choose_lead_person));//选择人员
        toolbarHelper.setTitle(getString(R.string.choose_sell_person_other));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);


    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        leadManMemberAdapter = new LeadManMemberAdapter(R.layout.leadmemberadapter, mDatasResources);
        recyclerViewInLeadData.setLayoutManager(new MyLinearLayoutManager(this));
        recyclerViewInLeadData.clearAnimation();
        recyclerViewInLeadData.setAdapter(leadManMemberAdapter);
        leadManMemberAdapter.notifyDataSetChanged();

        leadManMemberAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                LeadListItemBean leadListItemBean = (LeadListItemBean) adapter.getItem(position);

                CheckBox checkBoxInLeadMember = (CheckBox) view.findViewById(R.id.checkboxinleadmember);
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "点击了条目内容" + runManGroupHeadOrTeamCheck.getGroupUserName());

                if (leadListItemBean != null) {

                    int isChecked = leadListItemBean.getIsChecked();

                    if (isChecked == 0) {

                        for (int index = 0; index < mDatasResources.size(); index++) {

                            if (index == position) {
                                mDatasResources.get(index).setIsChecked(1);
                                checkBoxInLeadMember.setChecked(true);
                            } else {
                                mDatasResources.get(index).setIsChecked(0);
                                checkBoxInLeadMember.setChecked(false);
                            }

                        }

                    } else if (isChecked == 1) {//如果当前状态是已经被选中的状态

                        //全部置空
                        for (int ind = 0; ind < mDatasResources.size(); ind++) {
                            mDatasResources.get(ind).setIsChecked(0);
                            checkBoxInLeadMember.setChecked(false);
                        }

                    }

                    if (leadManMemberAdapter != null) {
                        leadManMemberAdapter.notifyDataSetChanged();
                    }

                }

            }
        });


        //暂时设置 仅仅只有下拉刷新，没有加载更多；
        refreshLayoutInLeadData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDatasResources != null && !mDatasResources.isEmpty()) {
                            mDatasResources.clear();
                        }

                        if (leadManMemberAdapter != null) {
                            leadManMemberAdapter.notifyDataSetChanged();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

        //点击【确定】勾选完毕 销售人员
        roundButtonSureChooseLead.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {

                RxBusLeadMember rxBusLeadMember = new RxBusLeadMember(ExtraValue.RXBUS_ARCHIVE_CUSTOMER_FORM_LEADSMEMBER);

                for (LeadListItemBean leadListItemBean : mDatasResources) {

                    if (leadListItemBean.getIsChecked() == 1) {
                        rxBusLeadMember.setLeadListItemBean(leadListItemBean);
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "当前选中的潜客客户是-->" + leadListItemBean.getCustomerName());
                        break;
                    }

                }

                //拦截
                if (ObjectUtils.isEmpty(rxBusLeadMember.getLeadListItemBean())) {
                    ToastUtils.showShort(R.string.choose_person);
                    return;
                }

                //只有一个单个点击
                CommUtils.checkDialog(mAlertView);

                String messageContent = StringUtils.getString(R.string.clear_add_choose) +
                        StringUtils.getString(R.string.bracket_left_lead) + rxBusLeadMember.getLeadListItemBean().getCustomerName() + StringUtils.getString(R.string.bracket_right_lead);

                mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                        messageContent,//提示内容，确定提交吗？
                        StringUtils.getString(R.string.clearcachecancel), //取消
                        new String[]{StringUtils.getString(R.string.clearcachetitlesure)},//确定，这里用【确定】更合适。
                        null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                    @Override
                    public void onItemClick(Object o, int position) {

                        if (position != AlertView.CANCELPOSITION) {

                            // TODO: 如果是从添加客户档案过来的，那么，发送消息给客户档案添加页面
                            RxBus.getInstance().post(rxBusLeadMember);

                            methodBack();

                        }

                    }
                });

                mAlertView.setCancelable(true);
                mAlertView.show();

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
        }


        if (NetworkUtils.isConnected()) {

            getServerDatas();

//            if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_EVALUATE_DETAIL_ACTIVITY) {
//
//                //为了获取【车辆评估】的二手车销售
//                getServerDatas_evaluate();
//
//            } else if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_REPAIR_DETAIL_ACTIVITY) {
//
//                //为了获取【车辆评估】的二手车销售
//                getServerDatas_bookingRepair();
//
//            } else if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_SIGNATURE_ADDSUBMIT_ACTIVITY) {
//
//                getServerDatas_signatureAddSubmit();
//
//            } else {
//                getServerDatas();
//
//            }

        } else {
            netWorkError();
        }

    }


    //获取人员列表信息
    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//      map.put(Parameterkey.saleType, extra_lead_list_item_bean.getLatentType());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETLATENTCUSTOMERLIST_URL);
        addLogUpLoadInfo.setUrlPath(ApiService.getLatentCustomerList_url);
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setAlertToUser(true);
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getLatentCustomerList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadsDataActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<LeadListItemBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        function_response_20002(serverCode, serverMessage, addLogUpLoadInfo, true);

                    }
                })).subscribe(new Consumer<ArrayList<LeadListItemBean>>() {
                    @Override
                    public void accept(ArrayList<LeadListItemBean> leadListItemBeanArrayList) throws Throwable {

                        if (leadListItemBeanArrayList != null && !leadListItemBeanArrayList.isEmpty()) {

                            if (mDatasResources != null) {
                                mDatasResources.addAll(leadListItemBeanArrayList);
                            }
                            //先判断外侧，是不是为空，为空就是新进入添加，不是空，就是有历史记录的

                        } else {
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (leadManMemberAdapter != null) {
                            leadManMemberAdapter.notifyDataSetChanged();
                        }


                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        function_apiException(apiException);

                    }
                });

    }


    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    @Override
    public void processExtraData() {

    }
}